"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008  Obol Software Pty Ltd

This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt

"""

from phunc.utils import dictfetch, get_formatted_address,get_whole_save_path,get_whole_file_name,get_file_name_by_id,get_index_list
from phunc.logger import logger
from phunc.template import Template as  Template



def atable(dbc, acviewname, query_string):	
        dbc.execute("SELECT * FROM ledger.%s" % acviewname)
        account = dictfetch(dbc)		
        ledgerid = acviewname.split('_')[0]
        if ledgerid == 'general':
                jpage = 'finance.py/journal_details?j='
        else:
                jpage = 'finance.py/sub_journal_details?sl=%s&amp;j=' % ledgerid
        
        html='''<table class="title title2 fin-table" >
                            <tr>
                                    <th>ID</th>
                                    <th>Date</th>
                                    <th>Description</th>
                                    <th>DR</th>
                                    <th>CR</th>
                            </tr>
                            {% for item in account %}
                            <tr>
                                    <td><a href="/bin/{{jpage}}{{item['journal_id']}}{{query_string}}">{{item['journal_id']}}</a></td>
                                    <td>{{item['date']}}</td>
                                    <td>{{item['description']}}</td>
                                    <td>{% if item['dr'] %}{{item['dr']}}{% else %}&nbsp;{% endif %}</td>
                                    <td>{% if item['cr'] %}{{item['cr']}}{% else %}&nbsp;{% endif %}</td>
                            </tr>
                            {% endfor %}
                    </table>
                    <div class="img-line">&nbsp;</div>
                            '''
        for item in account:
                dr = item['dr']
                cr = item['cr']
                if dr == None:
                        item['dr'] = ''
                if cr == None:
                        item['cr'] = ''
        content={
                'query_string': query_string.replace('?', '&amp;'),
                'account':account,
                'jpage':jpage
        }
        template = Template()
        template.parseString( html)
        return template.render( content )

#----------------------

def jtable(dbc, j, query_string):	
		dbc.execute('SELECT * FROM system.general_journal_item WHERE journal_id = ' + j)
		items = dictfetch(dbc)
		
		html = '''<table class="title title2 admin">
							<tr>
									<th>ID</th>
									<th>Description</th>                                    
									<th>DR</th>											
									<th>CR</th>                                    
							</tr>
							{% for item in items %}
									<tr>
										<td><a href="/bin/finance.py/show_account_details?a={{item['account_id']}}{{ query_string}}">{{item['account_id']}}</a></td>
										<td>{{HTMLEncode(item['description'])}}</td>
										{% if item['drcr']=='CR'%}
										<td></td>											
										<td>{{ str(item['amount'])}}</td>
										{% else %}
										<td>{{ str(item['amount'])}}</td>
										<td></td>
										{% endif %}
									</tr>
							{% endfor %}
					</table> '''
				
		content={
				'items':items,
				'query_string':query_string.replace('?', '&amp;')
		}
		template = Template()
		template.parseString(html)
		return template.render( content )

#----------------------

def sljtable(dbc, j, sl, ca, query_string):	
        dbc.execute('SELECT * FROM system.' + sl + '_journal_item WHERE journal_id = ' + j)
        sitems = dictfetch(dbc)
        dbc.execute('SELECT * FROM system.general_journal_item WHERE journal_id = ' + j)
        gitems = dictfetch(dbc)
        html = '''<table class="title title2 admin">
                            <tr>
                                    <th>ID</th>
                                    <th>Description</th>                                    
                                    <th>DR</th>											
                                    <th>CR</th>                                    
                            </tr>
                            {% for item in sitems %}
                                    <tr>
                                            <td><a href="/bin/finance.py/show_sub_account_details?sl={{sl}}&amp;a={{str(item['account_id'])}}{{query_string}}">{{item['account_id2']}}</a></td>
                                            <td>{{item['description']}}</td>
                                            {% if item['drcr']=='CR'%}
                                            <td></td>											
                                            <td>{{ str(item['amount'])}}</td>
                                            {% else %}
                                            <td>{{ str(item['amount'])}}</td>
                                            <td></td>
                                            {% endif %}
                                    </tr>
                            {% endfor %}
                            {% for item in gitems %}
                                    <tr>
                                            <td><a href="/bin/finance.py/show_account_details?a={{item['account_id']}}{{query_string}}">{{item['account_id']}}</a>
                                            </td>
                                            <td>{{item['description']}}{{item['flag']}}</td>
                                            {% if item['drcr']=='CR'%}
                                            <td></td>											
                                            <td>{{ str(item['amount'])}}</td>
                                            {% else %}                                            											
                                            <td>{{ str(item['amount'])}}</td>
                                            <td></td>
                                            {% endif %}
                                    </tr>
                            {% endfor %}
                    </table>
        '''
        for item in sitems:				
                dbc.execute("SELECT id FROM ledger." + sl + "_info WHERE id='" + ca + ".'||LPAD('" + str(item['account_id']) + "', 5, '0')")
                account_id = dictfetch(dbc,1)['id']
                item['account_id2']=account_id				
        for item in gitems:		
                if item['account_id'] == ca:
                        flag = '<span class="weaker"> (control entry)</span>'
                else:
                        flag = ''
                item['flag']=flag
                
        content={
                'sitems':sitems,
                'gitems':gitems,
                'query_string':query_string.replace('?', '&amp;'),
                'sl':sl
        }
        template = Template()
        template.parseString(html)
        return template.render( content )

#----------------------

def qtable(dbc, sql, uri_query_string=None, page=None):	
        dbc.execute(sql)
        table = dictfetch(dbc)
        template = Template()
        html_page='''
                <table class="center spacebelow" cellspacing="0">
                <tr>
                        {% for col in col_desc %}
                        <th>{{col[0]}}</th>
                        {% endfor %}
                </tr>
                {% for rec in recset %}
                <tr>
                        {% for col in col_desc %}
                                <td>{{rec[col[0]]}}</td>
                        {% endfor %}
                </tr>
                {% endfor %}
                </table>
                '''
        template.parseString( html_page )
        pre_page = page and page - 1 or 0
        next_page = page and page + 1 or 0
        content = {'col_desc':dbc.description,
                            'recset':table,
                            'uri_query_string':uri_query_string,
                            'page':page,
                            'pre_page':str(pre_page),
                            'next_page':str(next_page),
                         }
        return template.render( content )

#----------------------

def contacts_by_company(dbc, query_string,skin,sql,page,pagesize,url,page_params):
        html='''
        <div class="search">
                <div>&nbsp;</div>
                <form id="search" action="/bin/crm.py" method="post" onsubmit="">
						<fieldset>
                        <label for="entity_name">Name:</label>
                        <input id="entity_name" name="entity_name" type="text"{% if page_params.has_key('entity_name') %} value="{{page_params['entity_name']}}"{% endif %} />
                        <input name="submit" type="submit" value="Search" class="search-button" />
                        <input name="reset" type="button" value="Clear" onclick="clear_form();" class="search-button" />
						</fieldset>
                </form>
                <script type="text/javascript">
                function clear_form(){
                        document.getElementById('entity_name').value='';
                }
                </script>
                <div>&nbsp;</div>
                <ul> 
                        {% for a in index_list %}                            
                                <li><a href="/bin/crm.py?searchkey={{a}}">{{a}}</a></li>                            
                        {% endfor %}       
                </ul>
        </div>'''        
        page_split_setup={
                'cursor':dbc,
                'sql':sql,
                'skin':skin,
                'page':page,
                'pagesize':pagesize,
                'url':url,
                'params':page_params,
        }                        
        contacts = ControlPage(**page_split_setup)
        results=contacts.result
        page_split = contacts.createHtml() 
        content={
                'index_list':get_index_list(),
                'page_params':page_params,
        }
        template = Template()
        template.parseString(html)
        html = template.render( content )
        
##        dbc.execute("SELECT company_name, given_name, surname, phone, TRIM(COALESCE(email, ' ')) AS email, company_id, person_id FROM contact_info")
##        contacts = dictfetch(dbc)
        del_linkpart = '<a href="/bin/crm.py/delete_contact?pid='
        if page_params.has_key("entity_name") and page_params['entity_name'].strip():
                del_linkpart = '<a href="/bin/crm.py/delete_contact?entity_name=' +page_params['entity_name'].strip() + '&pid='
        if page_params.has_key("searchkey") and page_params['searchkey'].strip():
                del_linkpart = '<a href="/bin/crm.py/delete_contact?searchkey=' +page_params['searchkey'].strip() + '&pid='
                
        if len(results) > 0:		   
                if results[0]['company_id']:
                        previous_row_company_name = results[0]['company_name']
                        previous_row_company_link  = '<a href="/bin/crm.py/get_company_info?id=%d">%s</a>' % (results[0]['company_id'], results[0]['company_name'])
                        c_id_str = 'cid=' + str(results[0]['company_id']) + '&amp;'
                else:
                        previous_row_company_name  = results[0]['company_name']
                        previous_row_company_link  = 'No location'
                        c_id_str = ''
        else:
                previous_row_company_name  = ''	
                previous_row_company_link  = 'No location'
        html = html+'''
                <div class="title"><div>'''+previous_row_company_link+'''</div></div>       
        '''
        for contact in results:
                if contact['company_name'] != previous_row_company_name:
                        if contact['company_id']:
                                previous_row_company_name = contact['company_name']
                                previous_row_company_link  = '<a href="/bin/crm.py/get_company_info?id=%d%s">%s</a>' % (contact['company_id'], query_string.replace('?', '&amp;'), contact['company_name'].capitalize())
                                c_id_str = 'cid=' + str(contact['company_id']) + '&amp;'
                        else:
                                previous_row_company_name  = contact['company_name']
                                previous_row_company_link  = 'No location'
                                c_id_str = ''
                        html = html + '''    
                                        <div class="title">
                                            <div>'''+previous_row_company_link+'''</div>
                                        </div>
                        '''
                if not contact['email']:
                        email_link = '&nbsp;'
                else:
                        email_link = '<a href="mailto:' + contact['email'] + '">' + contact['email'] + '</a>'
                if contact['phone'] == None:
                        contact['phone'] = '&nbsp;'
                if len(contact['given_name'] + ' ' + contact['surname'] )>=20:
                    stab= '''
                             <dl class="fin">
                                    <dd><a href="/bin/crm.py/get_contact_detail?'''+c_id_str+'''pid='''+str(contact['person_id'])+query_string.replace('?', '&amp;') +'''" title="'''+contact['given_name'] + ' ' + contact['surname'] + '''" >'''+contact['given_name'] + ' ' + contact['surname'] + '''</a></dd>
                                    <dd>'''+contact['phone']+'''</dd>
                                    <dd>'''+email_link+'''</dd>
                                    <dt>''' + del_linkpart + str(contact['person_id']) + '''">del</a> <a href="/bin/crm.py/merge_contact_step1?'''+c_id_str+'''pid='''+str(contact['person_id']) + '''&iscustomer=''' + str(contact['iscustomer']) + '''&issupplier=''' + str(contact['issupplier']) + '''">merge</a></dt>
                           </dl>               
                    '''
                else:
                    stab= '''
                             <dl class="fin">
                                    <dd><a href="/bin/crm.py/get_contact_detail?'''+c_id_str+'''pid='''+str(contact['person_id'])+query_string.replace('?', '&amp;') +'''" >'''+contact['given_name'] + ' ' + contact['surname'] + '''</a></dd>
                                    <dd>'''+contact['phone']+'''</dd>
                                    <dd>'''+email_link+'''</dd>
                                    <dt>''' + del_linkpart + str(contact['person_id']) + '''">del</a> <a href="/bin/crm.py/merge_contact_step1?'''+c_id_str+'''pid='''+str(contact['person_id']) + '''&iscustomer=''' + str(contact['iscustomer']) + '''&issupplier=''' + str(contact['issupplier']) + '''">merge</a></dt>
                           </dl>               
                    '''
                html = html +stab
                #previous_row_company_name = contact['company_name']
        html = html + page_split
        return html;

#----------------------


#------------------------

def place_of_business_choice(dbc, company_id, validate=True, heading='Select from known locations'):
		#dbc.execute("SELECT * FROM system.place_of_business_info WHERE id IN (SELECT id FROM system.place_of_business WHERE company_id = " + company_id + ")")
		#---------------------------------template-------------------#						
		html = '''{% if len(matches)>0 %}
							<div class="new-oth">{{heading}}</div>
								<dl class="chek">
								{% for match in matches %}
												<dt>
															<input class="explain-color select{% if validate %} validate-one-if-none{% endif %}" type="checkbox" name="place_of_business_id"   value="{{str(match['id'])}}" onchange="hideUnhide(this, 'address-block', true)" />{{match['company_name']}}({{match['name']}})
												</dt>	
												<dd>{{match['format_address']}}</dd>
								{% endfor %}
								</dl>
					{% else %}
							""			 
					{% endif %}
		'''
		#---------------------------------template-------------------#
		dbc.execute("SELECT * FROM system.company_location_info WHERE id IN (SELECT id FROM system.location WHERE entity_id = " + company_id + ")")
		matches = dictfetch(dbc) 
		if len(matches)>0:
				for match in matches:
						match['format_address']=get_formatted_address(match, True)         
				content={
						'matches':matches,
						'heading':heading,				
						'validate':validate
				}
				template = Template()
				template.parseString(html)
				return template.render( content )
		else:
				return None
#-----------------------

def alt_location_choice(dbc, person_id, validate=True, heading='Select from known locations'):
		dbc.execute("SELECT * FROM system.person_location_info WHERE line1 NOTNULL AND person_id = %s" % person_id)
		matches = dictfetch(dbc)
		#---------------------------------template-------------------#
		html='''{% if len(matches)>0 %}
					<div class="new-oth">{{heading}}</div>
							<dl class="chek">
							{% for match in matches %}
									<dt>
											<input class="explain-color select {{validation_class}}" type="checkbox" name="alt_location_id" value="{{match['id']}}" onchange="hideUnhide(this, 'address-block', true)"/>{{match['title_bits']}}
											</dt>	
											<dd>{{match['format_address']}}</dd>						
									</dt>
							{% endfor %}
							</dl>
					{% else %}
							""
					{% endif %}
		'''
		#---------------------------------template-------------------#		
		if matches:
				validation_class = ''
				for match in matches:
						if match['type'] == 'place of business':						
								pob_id = match['id']
								dbc.execute("SELECT company_name, name FROM system.company_location_info WHERE id = %s" % pob_id)
								company_details = dictfetch(dbc, 1)
								title_bits = '%s, (%s)<br/>' % (company_details['company_name'], company_details['name'])
						else:
								title_bits = '%s<br/>' % match['type'].upper()
						match['title_bits']=title_bits
						match['format_address']=get_formatted_address(match, True)				
						if validate:
								validation_class = ' class="validate-one-if-none"'
				content={
						'matches':matches,
						'heading':heading,				
						'validation_class':validation_class,
				}
				template = Template()
				template.parseString(html)
				return template.render( content )
		else:
				return None
#------------------------

def contact_log(dbc, person_id, company_id, query_string,skin):		
        dbc.execute("SELECT * FROM contact_log WHERE entity_id = %s ORDER BY id DESC LIMIT 10" % person_id)
        recent_entries = dictfetch(dbc)
        dbc.execute("SELECT * FROM contact_log WHERE entity_id = %s AND action NOTNULL AND closed ISNULL AND id NOT IN (SELECT id FROM contact_log WHERE entity_id = %s ORDER BY id DESC LIMIT 10) ORDER BY id DESC" % (person_id, person_id))
        open_actions = dictfetch(dbc)		
        content={}
        content['query_string']=query_string.replace('?', '&amp;')
        content['person_id']=person_id
        content['company_id'] = company_id
        if company_id.upper() != 'NONE':
            cid_str = 'cid=' + company_id + '&amp;'
        else:
            cid_str = 'cid=&amp;'
    #---------------------------------template-------------------#
        html='''
        {% if len(recent_entries) > 0 %}     
        <div id="table">
                <dl class="dl-titile">
                         <dd class="re">Recent contact</dd>
                         <dd class="at">attachment</dd>
                         <dd class="ac">action</dd>
                         <dt>date closed</dt>
                </dl>
                <div id="change-bg">
                    {% for log_entry in recent_entries %}
                        {% if log_entry['flag']==0 %}
                            <dl class="dl-body  col-font">
                                     <dd class="re">
                                            <ul>
                                                   <li class="date">{{log_entry['log_date']}}</li>
                                                   <li class="contact">{{HTMLEncode(log_entry['comment'])}}</li>
                                                   <li class="edit-img"><a href="/bin/crm.py/get_person_log?pid={{person_id}}&amp;cid={{company_id}}&amp;edit={{log_entry['id']}}{{query_string}}"><img src="/{{skin}}/edit.gif" alt="edit" /></a></li>
                                            </ul>
                                     </dd>
                                    <dd class="at"><a href="{{log_entry['whole_file_name'][13:]}}">{{HTMLEncode(log_entry['filename'])}}</a></dd>
                                    <dd class="ac">{{HTMLEncode(log_entry['action'])}}</dd>
                                    <dt>{{log_entry['closed']}}</dt>
                            </dl>
                        {% else %}
                            <dl class="dl-body">
                                    <dd class="re">
                                            <ul>
                                                   <li class="date">{{log_entry['log_date']}}</li>
                                                   <li class="contact">{{HTMLEncode(log_entry['comment'])}}</li>
                                                   <li class="edit-img"><a href="/bin/crm.py/get_person_log?pid={{person_id}}&amp;cid={{company_id}}&amp;edit={{log_entry['id']}}{{query_string}}"><img src="/{{skin}}/edit.gif" alt="edit" /></a></li>
                                            </ul>
                                     </dd>
                                    <dd class="at"><a href="{{log_entry['whole_file_name'][13:]}}">{{HTMLEncode(log_entry['filename'])}}</a></dd>
                                    <dd class="ac">{{HTMLEncode(log_entry['action'])}}</dd>
                                    <dt>{{log_entry['closed']}}</dt>
                            </dl>
                        {% endif %}
                    {% endfor %}
                    {% for log_entry in open_actions %}
                            <dl class="dl-body">
                                    <dd class="re">
                                            <ul>
                                                   <li class="date">{{log_entry['log_date']}}</li>
                                                   <li class="contact">{{HTMLEncode(log_entry['comment'])}}</li>
                                                   <li class="edit-img"><a href="/bin/crm.py/get_person_log?pid={{person_id}}&amp;cid={{company_id}}&amp;edit={{log_entry['id']}}{{query_string}}"><img src="/{{skin}}/edit.gif" alt="edit" /></a></li>
                                            </ul>
                                     </dd>
                                    <dd class="at"><a href="{{log_entry['whole_file_name'][13:]}}">{{HTMLEncode(log_entry['filename'])}}</a></dd>
                                    <dd class="ac">{{HTMLEncode(log_entry['action'])}}</dd>
                                    <dt><a href="/bin/sle.py?pid={{person_id}}&amp;cid={{company_id}}&amp;close={{log_entry['id']}}{{query_string}}"><img src="/{{skin}}/del.gif" alt="del" /></a></dt>
                            </dl>
                    {% endfor %}
                </div>
        </div>
        {% else %}
        <div id="table">
                <dl class="dl-titile">
                         <dd class="re">Recent contact</dd>
                         <dd class="at">attachment</dd>
                         <dd class="ac">action</dd>
                         <dt>date closed</dt>
                </dl>
        </div>
        {% endif %}
        '''        
    #---------------------------------template-------------------#				
        if len(recent_entries) > 0:		
                for log_entry in recent_entries:
                        if log_entry['closed']:
                                closed = '%s' % log_entry['closed']
                                log_entry['flag']=0 #closed
                        else:                                
                                if log_entry['action']:
                                        log_entry['flag']=1 #not closed
                                        closed = '<a href="/bin/crm.py/get_person_log?pid=%s&amp;cid=%s&amp;close=%s"><img src="/%s/del.gif" alt="del" /></a>' % (person_id, company_id, log_entry['id'],skin)
                                else:
                                        log_entry['flag']=2 #no action
                                        closed = ''
                        log_entry['closed']=closed
                        log_entry['comment']=log_entry['comment'].strip().replace('\n', '<br/>')                        
                        log_entry['action']=max(log_entry['action'], '').strip().replace('\n', '<br/>')
                        if log_entry['filename']:
                                whole_file_path = get_whole_save_path(log_entry['entity_id'], log_entry['id'])
                                whole_file_name = get_whole_file_name(whole_file_path, get_file_name_by_id(log_entry['id'], log_entry['filename']))
                                log_entry['whole_file_path'] = whole_file_path
                                log_entry['whole_file_name'] = whole_file_name
                        else:
                                log_entry['filename']=''
                                log_entry['whole_file_path'] = '#'
                                log_entry['whole_file_name'] = ''
                for log_entry in open_actions:
                        log_entry['comment']=log_entry['comment'].strip().replace('\n', '<br/>')
                        log_entry['action']=max(log_entry['action'], '').strip().replace('\n', '<br/>') 
                        if log_entry['filename']:
                                whole_file_path = get_whole_save_path(log_entry['entity_id'], log_entry['id'])
                                whole_file_name = get_whole_file_name(whole_file_path, get_file_name_by_id(log_entry['id'], log_entry['filename']))
                                log_entry['whole_file_path'] = whole_file_path
                                log_entry['whole_file_name'] = whole_file_name
                        else:
                                log_entry['filename']=''
                                log_entry['whole_file_path'] = ''
                                log_entry['whole_file_name'] = ''
        content['recent_entries'] = recent_entries
        content['open_actions'] = open_actions
        content['skin'] = skin
        template = Template()
        template.parseString(html)
        return template.render( content )
#------------------------
def lcontact_log(dbc, person_id_list,company_id,skin):
		"""
			Get the conatct_log from person_id_list.
			Get contact_log from contact_log
			Get person's name from system.person
		"""
		content={}
		
		person_id = ",".join(["%s" % p['person_id'] for p in person_id_list])	
		dbc.execute("SELECT s.id, s.log_date, s.comment, COALESCE(s.action, ' ') AS action, s.closed, s.entity_id,e.given_name||' '||e.name as personname FROM contact_log s,system.entity e WHERE s.entity_id in (" + person_id + ") and s.entity_id=e.id ORDER BY s.id DESC LIMIT 10")
		recent_entries = dictfetch(dbc)
		dbc.execute("SELECT s.id, s.log_date, s.comment, COALESCE(s.action, ' ') AS action, s.closed, s.entity_id,e.given_name||' '||e.name as personname FROM contact_log s,system.entity e  WHERE s.entity_id in (" + person_id + ") AND action <> ' ' AND s.closed ISNULL AND s.id NOT IN (SELECT id FROM contact_log d WHERE d.entity_id in (" + person_id + ") ORDER BY d.id DESC LIMIT 10) AND s.entity_id = e.id ORDER BY s.id DESC")
		open_actions = dbc.fetchall()		
		
		add_entry_href = ''
		for log_entry in recent_entries:
				if log_entry['closed']:
						log_entry['closed'] = str(log_entry['closed'])
				else:
						if log_entry['action'] == ' ':
								log_entry['closed'] = ' '
						else:
								log_entry['closed'] = '<a href="/bin/crm.py/get_contact_detail?pid=' + str(log_entry['entity_id']) + '&amp;cid='+str(company_id)+'&amp;close=' + str(log_entry['id']) + '"><img src="/%s/del.gif" alt="del" /></a>'%skin
				log_entry['add_entry_href'] = '''<a href="/bin/crm.py/get_contact_detail?pid=''' + str(log_entry['entity_id']) + '''&amp;cid='''+str(company_id)+'''">'''		
				log_entry['comment']=log_entry['comment'].strip().replace('\n', '<br/>')
				log_entry['action']=log_entry['action'].strip().replace('\n', '<br/>')
		for log_entry in open_actions:
						add_entry_href = '''<a href="/bin/crm.py/get_contact_detail?pid=''' + str(log_entry['entity_id']) + '''&amp;cid='''+str(company_id)+'''">'''
						log_entry['add_entry_href']=add_entry_href
		content['recent_entries']=recent_entries  
		content['open_actions']=open_actions
#---------------------------------template-------------------#
		html='''
							<table id="contact-log" class="title title2 crm">                               
									<tr>
											<th colspan="2">Recent contact</th>
											<th>action item</th>
											<th>action</th>
											<th id="border-0">date closed</th>
									</tr>		
                                {% if len(recent_entries)>0 %}     
                                    {% for log_entry in recent_entries %}
                                    <tr>
                                            <td >{{log_entry['log_date']}}</td>
                                            <td >{{ log_entry['add_entry_href']}}{{log_entry['personname']}}</a></td>
                                            <td >{{ log_entry['comment']}}</td>
                                            <td >{{log_entry['action']}}</td>
                                            <td >{{log_entry['closed']}}</td>
                                    </tr>
                                    {% endfor %}							
                                    {% for log_entry in open_actions %}
                                    <tr>
                                            <td>{{log_entry['log_date']}}</td>
                                            <td >{{log_entry['add_entry_href']{{log_entry['personname']}}</a></td>
                                            <td >{{log_entry['log_date']}}</td>
                                            <td >{{log_entry['comment']}}</td>
                                            <td><a href="/bin/crm.py/get_person_log?id={{str(log_entry['entity_id'])}}&amp;close={{str(log_entry['id'])}}">*</a></td>
                                    </tr>   
                                    {% endfor %}
                                    {% endif %}
                        </table>
					'''
#---------------------------------template-------------------#
		template = Template()
		template.parseString(html)
		return template.render( content )
#----------page split---------#
class Page:
        def __init__(self,cursor=None,sql=None,pagesize=10):                
                self.cursor = cursor 
                self.sql = sql
                self.pagesize = pagesize
                self.page = 1                
                self.pagecount = 0
        def __getitem__(self,name):
                if name=='pagecount':
                        return self.pagecount
        def getPage(self):
                return self.page
        def setPage(self,page):                
                self.page = int(page)
        def countPage(self):
                logger.debug(self.cursor)
                logger.debug(self.sql)
                self.cursor.execute( self.sql )
                result = self.cursor.rowcount
                logger.debug(result)
                if self.cursor==None or self.sql==None or self.sql.strip()=="":
                        return
                else:
                        try:
                                self.cursor.execute( self.sql )
                                result = self.cursor.rowcount
                                if result % self.pagesize ==0:
                                        self.pagecount = result / self.pagesize
                                else:
                                        self.pagecount = result / self.pagesize + 1
                                return
                        except:
                                return
    
        def getResultPage(self):
                result_map = {'result':[],'pagecount':0}
                if self.cursor==None or self.sql==None or self.sql.strip()=="":
                        return result
                else:
                        extend_sql = self.sql + ' LIMIT %d OFFSET '%int(self.pagesize) + str((self.page - 1) * self.pagesize)
                        logger.debug(extend_sql)
                        try:
                                self.cursor.execute( extend_sql )
                                result_map['result'] = dictfetch(self.cursor)
                                result_map['pagecount'] = self.pagecount
                                return result_map
                        except:
                                return result_map
class ControlPage:
        '''
        #flag=1:just for the loginpage
        #default flag=0
        '''
        def __init__(self,cursor=None,sql=None,skin=None,page=1,pagesize=10,url=None,params={},flag=0):
                self.skin = skin
                self.page = int(page)
                self.url = url
                self.query_string = '' 
                self.flag = flag
                if params:
                        for key,value in params.iteritems():
                                self.query_string = self.query_string+"&amp;%s=%s"%(str(key),str(value))
                pageObj = Page(cursor,sql,pagesize)
                pageObj.setPage(page)
                pageObj.countPage()
                logger.debug(pageObj.pagecount)
                self.result = pageObj.getResultPage()['result']
                self.pagecount = pageObj.getResultPage()['pagecount']
        def __getitem__(self,name):
                if name == 'result':
                        return self.result
                if name == 'pagecount':
                        return self.pagecount
        def createHtml(self):
                html=""
                if self.pagecount<=1:
                        if self.flag == 1:
                                html=html+'''
                                    <div>'''
                        else:
                                html=html+'''
                                    <div class="next">
                                        <div>'''
                        html=html+'''
                                <a href="#"><img src="/%s/next-left.gif" alt="" /></a>
                                <a href="#"><img src="/%s/next-left2.gif" alt="" /></a>
                                <a href="#">1</a>
                                <a href="#"><img src="/%s/next-right2.gif" alt="" /></a>
                                <a href="#"><img src="/%s/next-right.gif" alt="" /></a>
                            '''%(self.skin,self.skin,self.skin,self.skin)
                        if self.flag == 1:
                                html=html+'''
                                    </div>'''
                        else:
                                html=html+'''
                                    </div>
                                </div>'''
                elif self.pagecount<=10:
                        if self.page==1:
                                if self.flag == 1:
                                        html=html+'''
                                            <div>'''
                                else:
                                        html=html+'''
                                            <div class="next">
                                                <div>'''
                                html=html+'''
                                        <a href="#"><img src="/%s/next-left.gif" alt="" /></a>
                                        <a href="#"><img src="/%s/next-left2.gif" alt="" /></a>
                                        <span>1</span>'''%(self.skin,self.skin)                        
                                for i in range(self.pagecount-1):
                                        html=html+'''
                                        <a href="%s?page=%s%s">%s</a>'''%(self.url,str(i+2),self.query_string,str(i+2))
                                html=html+'''                       
                                        <a href="%s?page=%s%s"><img src="/%s/next-right2.gif" alt="" /></a>
                                        <a href="%s?page=%s%s"><img src="/%s/next-right.gif" alt="" /></a>
                                    '''%(self.url,str(self.page+1),self.query_string,self.skin,self.url,str(self.pagecount),self.query_string,self.skin)
                                if self.flag == 1:
                                        html=html+'''
                                            </div>'''
                                else:
                                        html=html+'''
                                            </div>
                                        </div>'''
                        elif 1<self.page<self.pagecount:
                                if self.flag == 1:
                                        html=html+'''
                                            <div>'''
                                else:
                                        html=html+'''
                                            <div class="next">
                                                <div>'''
                                html=html+'''
                                        <a href="%s?page=1%s"><img src="/%s/next-left.gif" alt="" /></a>
                                        <a href="%s?page=%s%s"><img src="/%s/next-left2.gif" alt="" /></a>'''%(self.url,self.query_string,self.skin,self.url,str(self.page-1),self.query_string,self.skin)
                                for i in range(self.pagecount):
                                        if i+1==self.page:
                                                html=html+'''<span>%s</span>'''%str(i+1)
                                        else:
                                                html=html+'''
                                                <a href="%s?page=%s%s">%s</a>'''%(self.url,str(i+1),self.query_string,str(i+1))
                                html=html+'''                        
                                        <a href="%s?page=%s%s"><img src="/%s/next-right2.gif" alt="" /></a>
                                        <a href="%s?page=%s%s"><img src="/%s/next-right.gif" alt="" /></a>
                                    '''%(self.url,str(self.page+1),self.query_string,self.skin,self.url,str(self.pagecount),self.query_string,self.skin)
                                if self.flag == 1:
                                        html=html+'''
                                            </div>'''
                                else:
                                        html=html+'''
                                            </div>
                                        </div>'''
                        elif self.page>=self.pagecount:
                                if self.flag == 1:
                                        html=html+'''
                                            <div>'''
                                else:
                                        html=html+'''
                                            <div class="next">
                                                <div>'''
                                html=html+'''
                                        <a href="%s?page=1%s"><img src="/%s/next-left.gif" alt="" /></a>
                                        <a href="%s?page=%s%s"><img src="/%s/next-left2.gif" alt="" /></a>'''%(self.url,self.query_string,self.skin,self.url,str(self.page-1),self.query_string,self.skin)                        
                                for i in range(self.pagecount):
                                        if i+1==self.pagecount:
                                                html=html+'''<span>%s</span>'''%str(i+1)
                                        else:
                                                html=html+'''
                                                <a href="%s?page=%s%s">%s</a>'''%(self.url,str(i+1),self.query_string,str(i+1)) 
                                html=html+'''
                                        <a href="#"><img src="/%s/next-right2.gif" alt="" /></a>
                                        <a href="#"><img src="/%s/next-right.gif" alt="" /></a>
                                        '''%(self.skin,self.skin)
                                if self.flag == 1:
                                        html=html+'''
                                            </div>'''
                                else:
                                        html=html+'''
                                            </div>
                                        </div>'''   
                        else:
                                pass
                else:
                        if self.page==1:
                                if self.flag == 1:
                                        html=html+'''
                                            <div>'''
                                else:
                                        html=html+'''
                                            <div class="next">
                                                <div>'''
                                html=html+'''
                                        <a href="#"><img src="/%s/next-left.gif" alt="" /></a>
                                        <a href="#"><img src="/%s/next-left2.gif" alt="" /></a>'''%(self.skin,self.skin)
                                html=html+'''
                                        <select name="jumpMenu" id="jumpMenu" onchange="MM_jumpMenu(this,'%s','%s')">'''%(self.url,self.query_string)
                                for i in range(self.pagecount):
                                        if i+1==int(self.page):
                                                html=html+'''
                                                <option value='%s' selected='selected'>%s</option>'''%(str(i+1),str(i+1))
                                        else:
                                                html=html+'''
                                                <option value='%s'>%s</option>'''%(str(i+1),str(i+1))
                                html=html+'''
                                        </select>&nbsp;of&nbsp;%s
                                        <a href="%s?page=%s%s"><img src="/%s/next-right2.gif" alt="" /></a>
                                        <a href="%s?page=%s%s"><img src="/%s/next-right.gif" alt="" /></a>
                                    '''%(str(self.pagecount),self.url,str(self.page+1),self.query_string,self.skin,self.url,str(self.pagecount),self.query_string,self.skin)
                                if self.flag == 1:
                                        html=html+'''
                                            </div>'''
                                else:
                                        html=html+'''
                                            </div>
                                        </div>'''                                
                        elif 1<int(self.page)<int(self.pagecount):
                                if self.flag == 1:
                                        html=html+'''
                                            <div>'''
                                else:
                                        html=html+'''
                                            <div class="next">
                                                <div>'''
                                html=html+'''
                                        <a href="%s?page=1%s"><img src="/%s/next-left.gif" alt="" /></a>
                                        <a href="%s?page=%s%s"><img src="/%s/next-left2.gif" alt="" /></a>'''%(self.url,self.query_string,self.skin,self.url,str(self.page-1),self.query_string,self.skin)
                                html=html+'''
                                        <select name="jumpMenu" id="jumpMenu" onchange="MM_jumpMenu(this,'%s','%s')">'''%(self.url,self.query_string)
                                for i in range(self.pagecount):
                                        if i+1==int(self.page):
                                                html=html+'''
                                                <option value='%s' selected='selected'>%s</option>'''%(str(i+1),str(i+1))
                                        else:
                                                html=html+'''
                                                <option value='%s'>%s</option>'''%(str(i+1),str(i+1))
                                html=html+'''
                                        </select>&nbsp;of&nbsp;%s               
                                        <a href="%s?page=%s%s"><img src="/%s/next-right2.gif" alt="" /></a>
                                        <a href="%s?page=%s%s"><img src="/%s/next-right.gif" alt="" /></a>
                                    '''%(str(self.pagecount),self.url,str(self.page+1),self.query_string,self.skin,self.url,str(self.pagecount),self.query_string,self.skin)
                                if self.flag == 1:
                                        html=html+'''
                                            </div>'''
                                else:
                                        html=html+'''
                                            </div>
                                        </div>'''   
                        elif self.page>=self.pagecount:
                                if self.flag == 1:
                                        html=html+'''
                                            <div>'''
                                else:
                                        html=html+'''
                                            <div class="next">
                                                <div>'''
                                html=html+'''
                                        <a href="%s?page=1%s"><img src="/%s/next-left.gif" alt="" /></a>
                                        <a href="%s?page=%s%s"><img src="/%s/next-left2.gif" alt="" /></a>'''%(self.url,self.query_string,self.skin,self.url,str(self.page-1),self.query_string,self.skin)
                                html=html+'''
                                        <select name="jumpMenu" id="jumpMenu" onchange="MM_jumpMenu(this,'%s','%s')">'''%(self.url,self.query_string)
                                for i in range(self.pagecount):
                                        if i+1==self.page:
                                                html=html+'''
                                                <option value='%s' selected='selected'>%s</option>'''%(str(i+1),str(i+1))
                                        else:
                                                html=html+'''
                                                <option value='%s'>%s</option>'''%(str(i+1),str(i+1))
                                html=html+'''
                                        </select>&nbsp;of&nbsp;%s                              
                                        <a href="#"><img src="/%s/next-right2.gif" alt="" /></a>
                                        <a href="#"><img src="/%s/next-right.gif" alt="" /></a>
                                    '''%(str(self.pagecount),self.skin,self.skin)
                                if self.flag == 1:
                                        html=html+'''
                                            </div>'''
                                else:
                                        html=html+'''
                                            </div>
                                        </div>'''
                        else:
                                pass 
                return html
